package com.ev.apis.controller.asl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.ev.apis.model.DsResultResponse;
import com.ev.asl.constant.AslConstant;
import com.ev.asl.domain.AslBarCodeDO;
import com.ev.asl.domain.AslBarCodeTrayDO;
import com.ev.asl.dto.AslBarCodeParam;
import com.ev.asl.dto.AslBarCodeTrayParam;
import com.ev.asl.service.AslBarCodeService;
import com.ev.asl.service.KisBasicsService;
import com.ev.asl.vo.voBillOfPull.KisReceiveStockVo;
import com.ev.custom.domain.MaterielDO;
import com.ev.custom.service.MaterielService;
import com.ev.framework.annotation.EvApiByToken;
import com.ev.framework.utils.R;

import com.ev.mes.domain.ProductionPlanDO;

import com.ev.mes.service.ProductionPlanService;
import com.ev.system.service.OpLogService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 姚家乐
 * @since 2021/6/21 15:59
 */
@Api(value = "/", tags = "条码管理API")
@RestController
@Slf4j
public class AslBarCodeApiController {

    @Autowired
    private AslBarCodeService service;

    @Autowired
    private KisBasicsService kisBasicsService;

    @Autowired
    private ProductionPlanService productionPlanService;

    @Autowired
    private MaterielService materielService;

    @Autowired
    private OpLogService opLogService;

    /**
     * 批量删除条码(逻辑删除)
     * @param barCodeId
     * @return
     */
    @ApiOperation("批量删除条码")
    @EvApiByToken(value = "/apis/aslBarCode/batchRemove", method = RequestMethod.POST, apiTitle = "批量删除条码")
    public R batchRemove(@ApiParam(value = "条码Ids:List",required = true)@RequestParam List<Integer> barCodeId){
        if (ObjectUtils.isEmpty(barCodeId) || barCodeId.size()  <= 0){
            return R.error("请选择条码数据！");
        }
        List<AslBarCodeDO> bars = service.listByIds(barCodeId);
        List<AslBarCodeDO> isTrayed = bars.stream().filter(bar -> !ObjectUtils.isEmpty(bar.getTrayId()) && !bar.getTrayId().equals(0l)).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(isTrayed) && isTrayed.size()  > 0){
            return R.error("所选条码已生成托盘码，请先清除！");
        }

        List<Long> planIds = bars.stream().filter(bar -> !ObjectUtils.isEmpty(bar.getUuid())).map(AslBarCodeDO::getUuid).distinct().collect(Collectors.toList());
        List<ProductionPlanDO> planDOS = new ArrayList<>(); //条码绑定的生产计划
        Map<Long, ProductionPlanDO> plansById = new HashMap<>();
        if (!ObjectUtils.isEmpty(planIds)){
            HashMap<String, Object> planMap = new HashMap<>();
            planMap.put("ids",planIds);
            planDOS = productionPlanService.list(planMap);
        }
        if (ObjectUtil.isNotEmpty(planDOS)){
            plansById = planDOS.stream().collect(Collectors.toMap(plan -> plan.getId(), plan -> plan));
        }

        for (AslBarCodeDO entity : bars) {
            if (ObjectUtil.isNotEmpty(entity.getUuid()) && ObjectUtil.isNotEmpty(plansById)){
                ProductionPlanDO planDO = plansById.get(entity.getUuid());
                BigDecimal lotNoCount = ObjectUtil.isEmpty(planDO.getLotNoCount()) ? new BigDecimal(1) : planDO.getLotNoCount();
                planDO.setLotNoCount(lotNoCount.subtract(new BigDecimal(1)));
            }
        }
        if (ObjectUtil.isNotEmpty(plansById)){
            productionPlanService.batchUpdate(planDOS);
        }
        return service.batchRemove(barCodeId);
    }

    /**
     * 同步条码管理的信息
     * @return
     */
    @ApiOperation("同步条码管理的信息")
    @EvApiByToken(value = "/apis/aslBarCode/sync", method = RequestMethod.GET, apiTitle = "获取条码管理列表信息")
    public R syncAslBarCode(){
        return service.sync();
    }

    /**
     * 获取条码管理列表信息
     * @param pageno
     * @param pagesize
     * @param productionPlanNo
     * @param seriesNumber
     * @param productName
     * @param bagging
     * @param status
     * @return
     */
    @ApiOperation("获取条码管理列表信息")
    @EvApiByToken(value = "/apis/aslBarCode/list", method = RequestMethod.POST, apiTitle = "获取条码管理列表信息")
    public R list(@ApiParam(value = "当前第几页", required = true) @RequestParam(value = "pageno", defaultValue = "1") Integer pageno,
                  @ApiParam(value = "一页多少条", required = true) @RequestParam(value = "pagesize", defaultValue = "20") Integer pagesize,
                  @ApiParam(value = "生产任务单号") @RequestParam(value = "productionPlanNo", defaultValue = "", required = false) String productionPlanNo,
                  @ApiParam(value = "序列号") @RequestParam(value = "seriesNumber", defaultValue = "", required = false) String seriesNumber,
                  @ApiParam(value = "产品名称") @RequestParam(value = "startTime", required = false) Date startTime,
                  @ApiParam(value = "产品名称") @RequestParam(value = "endTime", required = false) Date endTime,
                  @ApiParam(value = "产品名称") @RequestParam(value = "productName", defaultValue = "", required = false) String productName,
                  @ApiParam(value = "是否套袋（0：否，1是）") @RequestParam(value = "bagging", defaultValue = "", required = false) Integer bagging,
                  @ApiParam(value = "状态(0:待处理,1:已处理,2:已清除)") @RequestParam(value = "status", defaultValue = "", required = false) Integer status) {
        AslBarCodeParam param = new AslBarCodeParam();
        param.setPageNo(pageno);
        param.setPageSize(pagesize);
//        params.put("offset",(pageno-1)*pagesize);
//        params.put("limit",pagesize);

        param.setOffset((pageno-1)*pagesize);
        param.setLimit(pagesize);
        param.setProductionPlanNo(productionPlanNo);
        param.setSeriesNumber(seriesNumber);
        param.setProductName(productName);
        param.setBagging(bagging);
        param.setStartTime(startTime);
        param.setEndTime(endTime);
        param.setStatus(status);
        Integer total = service.count(param);
        Map<String,Object> result = Maps.newHashMap();
        result.put("showTrayQrCode",false);
        if (total > 0){
            List<AslBarCodeDO> data = service.list(param);
            result.put("data", new DsResultResponse(pageno,pagesize,total,data));
            if (StringUtils.hasLength(productName) && (Objects.nonNull(bagging) && AslConstant.ONE.equals(bagging))){
                result.put("showTrayQrCode",true);
            }
        }
        return R.ok(result);
    }

    /**
     * 套袋标签
     * @param id
     * @return
     */
    @ApiOperation("套袋标签(选中点击套袋标签按钮后，获取套袋标签的信息，同时改变‘是否套袋’为已套袋)")
    @EvApiByToken(value = "/apis/aslBarCode/baggingLabel",
            method = RequestMethod.GET,
            apiTitle = "套袋标签(选中点击套袋标签按钮后，获取套袋标签的信息，同时改变‘是否套袋’为已套袋)")
    public R baggingLabel(@ApiParam(value = "条码管理主键ID", required = true) @RequestParam(value = "id", defaultValue = "") Long id) {
        Map<String, Object> result = Maps.newHashMap();
        AslBarCodeDO entity = service.get(id);
        if (AslConstant.YES.equals(entity.getScrapStatus())){
            return R.error("报废状态不能生成二维码");
        }
        entity.setBagging(AslConstant.YES);
        entity.setStatus(AslConstant.ONE);
        if (service.update(entity) >0){
            result.put("data",entity);
            return R.ok(result);
        }
        return R.error();
    }

    /**
     * 查找托盘信息
     * @param id
     * @return
     */
    @ApiOperation("查找托盘信息")
    @EvApiByToken(value = "/apis/aslBarCode/getTray",
            method = RequestMethod.GET,
            apiTitle = "查找托盘信息")
    public R getTray(@ApiParam(value = "查找托盘信息", required = true) @RequestParam(value = "id", defaultValue = "") Long id,
                     @ApiParam(value = "1-入库；2-出库", required = true) @RequestParam(value = "type", defaultValue = "") Long type) {
        Map<String, Object> result = Maps.newHashMap();
        result = service.getTray(id,type);
        if (result == null){
            return R.error();
        }
        return R.ok(result);
    }

    /**
     * 查找托盘信息
     * @return
     */
    @ApiOperation("查找托盘信息")
    @EvApiByToken(value = "/apis/aslBarCode/getFacility",
            method = RequestMethod.GET,
            apiTitle = "查找托盘信息")
    public R getFacility(@ApiParam(value = "查找托盘信息", required = true) @RequestParam(value = "locationId", defaultValue = "") Long locationId,
                         @ApiParam(value = "查找托盘信息", required = true) @RequestParam(value = "factilyId", required = false) Long factilyId) {

        log.error("==========================pda扫库位码查询库存======================================");
        Map<String, Object> result = Maps.newHashMap();
        List<Map<String, Object>> data = service.getFacilityTray(locationId);
        String filter = "and 物料名称='HBGE' and  规格型号 is not null " ;
        if(ObjectUtil.isNotEmpty(locationId)) filter = filter + "and 仓位ID='" + locationId + "'";
        if(ObjectUtil.isNotEmpty(factilyId)) filter = filter + "and 仓库ID='" + factilyId + "'";
        Triple<Boolean, String, List<KisReceiveStockVo>> stockList = kisBasicsService.realTimeStockBalanceEnquiry2(filter);
        if (!stockList.getLeft()){
            result.put("data",data);
            return R.ok(result);
        }
        List<KisReceiveStockVo> stockVos = stockList.getRight();
        data = stockVos.stream().map(stockVo -> {
            HashMap<String, Object> item = new HashMap<>();
            item.put("productName", stockVo.getFItemName());
            item.put("batchNo", stockVo.getFBatchNo());
            item.put("count", stockVo.getFQty());
            return item;
        }).collect(Collectors.toList());
        result.put("data",data);
        return R.ok(result);
    }


    /**
     * 托盘二维码（生成二维码）
     *  一个托盘中放同一个型号的桶、同一个生产任务单
     * @param integers
     * @return
     */
    @ApiOperation("托盘二维码（生成二维码）将四个条码数据生成二维码，并且存储到托盘管理表中")
    @EvApiByToken(value = "/apis/aslBarCode/trayQrCode",
            method = RequestMethod.POST,
            apiTitle = "托盘二维码（生成二维码）将四个条码数据生成二维码，并且存储到托盘管理表中")
    @Transactional
    public R trayQrCode(@ApiParam(value = "条码管理主键ID数组", required = true) @RequestParam(value = "ids") List<Integer> integers){
//        if (ids != null && ids.length  == 4){
        if (ObjectUtils.isEmpty(integers) || integers.size()  <= 0){
            return R.error("请选择条码数据！");
        }
        if (integers.size()  > 4){
            return R.error("一个托盘中不得多于四个桶！");
        }
        List<AslBarCodeDO> resultList = service.listByIds(integers);
        List<Long> trayIds = resultList.stream().map(bar -> bar.getTrayId()).distinct().collect(Collectors.toList());
        if(trayIds.size()==1){
            Long trayId = trayIds.get(0);
            Integer sum = service.countByTaryId(trayId);
            if(sum==integers.size()){
                AslBarCodeTrayDO tray = service.getTrayById(trayId);
                Map<String,Object> result = Maps.newHashMap();
                result.put("productId",tray.getProductId());
                result.put("productName",tray.getProductName());
                result.put("id",tray.getId());
                result.put("batch",tray.getBatchNos());
                result.put("sum",resultList.size());
                result.put("status",0);
                return R.ok(result);
            }

        }
        List<Long> productIds = resultList.stream().map(bar -> bar.getProductId()).distinct().collect(Collectors.toList());
        if (productIds.size()  > 1){
            return R.error("请选择同一种产品！");
        }
        List<Long> planIds = resultList.stream().map(bar -> bar.getUuid()).distinct().collect(Collectors.toList());
        if (planIds.size()  > 1){
            return R.error("请选择同一个生成计划！");
        }
        List<AslBarCodeDO> isTrayed = resultList.stream().filter(bar -> !ObjectUtils.isEmpty(bar.getTrayId()) && !bar.getTrayId().equals(0l)).collect(Collectors.toList());
        List<AslBarCodeDO> isBagging = resultList.stream().filter(bar -> ObjectUtils.isEmpty(bar.getBagging()) && bar.getBagging().equals(1)).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(planIds) && planIds.size()>1){
            return R.error("请选择同一个生产计划下的条码！");
        }
//        resultList.stream().

        //1、校验重复生成托盘码的桶 如果这些桶中存在生成过二维码的，只有当现在生成二维码的桶与之前生成二维码的桶完全一致时才进行下一步
        if (!ObjectUtils.isEmpty(isTrayed) && isTrayed.size()>0){
            List<Long> trays = isTrayed.stream().map(AslBarCodeDO::getTrayId).distinct().collect(Collectors.toList());
            //如果有条码已经生成过托盘码，检查四个条码是否都是同一个托盘码
            //检查条码的托盘码是否都相同
            if ((isTrayed.size() != integers.size()) || trays.size() > 1){
                log.error("===============isTrayed:{},integers:{},trays:{} ",isTrayed.size(),integers.size(),trays.size());
                return R.error("选择的数据中存在生成过的条码！");
            }
            if ((isBagging.size() != integers.size()) && trays.size() > 1){
                log.error("===============isBagging:{},integers:{},trays:{} ",isBagging.size(),integers.size(),trays.size());
                return R.error("选择的数据中存在同步失败的条码！");
            }
            //检查条码数量是否和上次生成托盘的条码数量一致
            AslBarCodeParam codeParam = new AslBarCodeParam();
            codeParam.setTrayId(isTrayed.get(0).getTrayId());
            List<AslBarCodeDO> list = service.list(codeParam);
            if (list.size() != integers.size()){
                log.error("===============list:{},integers:{},trays:{} ",list.size(),integers.size(),trays.size());
                return R.error("选择的数据中存在生成过的条码！");
            }
            if(service.updateStatus(isTrayed.get(0).getTrayId()) != 1){
                return R.error("生成错误！");
            };
        }

        List<AslBarCodeDO> aaa = resultList.stream().filter(tray -> !ObjectUtils.isEmpty(tray.getUuid())).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(aaa) || aaa.size() != integers.size()){
            return R.error("有条码未绑定生产计划！");
        }
        List<Long> bbb = aaa.stream().map(AslBarCodeDO::getUuid).distinct().collect(Collectors.toList());
        if (ObjectUtils.isEmpty(bbb) || bbb.size() > 1){
            return R.error("所选条码属于不同生产计划！");
        }
        //2、生成托盘二维码
        AslBarCodeDO codeDO = resultList.get(AslConstant.ZERO);
        List<String> seriesNumbers = resultList.stream().map(AslBarCodeDO::getSeriesNumber).collect(Collectors.toList());
        List<String> batchNos = resultList.stream().map(AslBarCodeDO::getBatchNo).collect(Collectors.toList());
        List<String> productionPlanNo = resultList.stream().map(AslBarCodeDO::getProductionPlanNo).collect(Collectors.toList());

        AslBarCodeTrayDO trayEntity = new AslBarCodeTrayDO();
        trayEntity.setProductCode(codeDO.getProductCode());
        trayEntity.setStatus(1);
        trayEntity.setProDept(codeDO.getProDept());
        trayEntity.setSum(resultList.size());
        trayEntity.setProductionPlanNo(codeDO.getProductionPlanNo());
        trayEntity.setProductName(codeDO.getProductName());
        trayEntity.setProductModel(codeDO.getProductModel());
        trayEntity.setSeriesNumbers(JSON.toJSONString(seriesNumbers));
        trayEntity.setBatchNos(String.join(",",batchNos));
        trayEntity.setProductId(codeDO.getProductId());
        trayEntity.setProductionPlanNos(JSON.toJSONString(productionPlanNo));
        trayEntity.setProductionPlanId(codeDO.getUuid());
        service.traySave(trayEntity);

        for (AslBarCodeDO entity : resultList) {
            entity.setTrayId(trayEntity.getId());
            entity.setStatus(1);
        }
        service.batchUpdate(resultList);
        Map<String,Object> result = Maps.newHashMap();
        result.put("productId",codeDO.getProductId());
        result.put("productName",codeDO.getProductName());
        result.put("id",trayEntity.getId());
        result.put("batch",trayEntity.getBatchNos());
        result.put("sum",resultList.size());
        result.put("status",0);
        return R.ok(result);
    }

    @ApiOperation("批量生成托盘二维码（生成二维码）将四个条码数据生成二维码，并且存储到托盘管理表中")
    @EvApiByToken(value = "/apis/aslBarCode/bachTrayQrCode",
            method = RequestMethod.POST,
            apiTitle = "批量生成托盘二维码（生成二维码）将四个条码数据生成二维码，并且存储到托盘管理表中")
    @Transactional(rollbackFor = Exception.class)
    public R bachTrayQrCode(@ApiParam(value = "条码管理主键ID数组", required = true) @RequestParam(value = "ids") List<Integer> integers){
        List<Integer> newIntegers = new ArrayList<>();
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> result = Maps.newHashMap();
        while(integers.size()>0){
            newIntegers.clear();
            for (int i = 0; i < 1 ;) {
                if(newIntegers.size()==4 || integers.size() == 0){
                    break;
                }
                newIntegers.add(integers.get(i));
                integers.remove(i);
            }
            R r = trayQrCode(newIntegers);
            if(500==Integer.valueOf(r.get("code").toString())){
                //当一组条码生成失败时手动回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return r;
            }
            r.remove("code");
            r.remove("msg");
            list.add(r);
        }
        result.put("list",list);
        return R.ok(result);
    }

//    public static void main(String[] args) {
//        BigDecimal a = null;
//        BigDecimal add = a.add(BigDecimal.ONE);
//    }
    /**
     * 将条码绑定生产计划
     * @param integers
     * @return
     */
    @ApiOperation("将条码绑定生产计划")
    @EvApiByToken(value = "/apis/aslBarCode/bindPlan",method = RequestMethod.GET, apiTitle = "将条码绑定生产计划")
    @Transactional
    public R bindPlan(@ApiParam(value = "条码管理主键ID数组", required = true) @RequestParam(value = "ids") List<Integer> integers,
                      @ApiParam(value = "生产计划主键id", required = true) @RequestParam(value = "planId") Long planId){
        if (ObjectUtils.isEmpty(integers) || integers.size()  <= 0){
            return R.error("请选择条码数据！");
        }
        List<AslBarCodeDO> bars = service.listByIds(integers);
        List<AslBarCodeDO> isTrayed = bars.stream().filter(bar -> !ObjectUtils.isEmpty(bar.getTrayId()) && !bar.getTrayId().equals(0l)).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(isTrayed) && isTrayed.size()  > 0){
            return R.error("所选条码已生成托盘码，请先清除！");
        }
        //1076
        List<Long> planIds = bars.stream().filter(bar -> !ObjectUtils.isEmpty(bar.getUuid())).map(bar -> bar.getUuid()).collect(Collectors.toList());
        List<ProductionPlanDO> planDOS = new ArrayList<>();
        Map<Long, ProductionPlanDO> plansMapById = new HashMap<>();
        if (!ObjectUtils.isEmpty(planIds)){
            HashMap<String, Object> planMap = new HashMap<>();
            planMap.put("ids",planIds);
            planDOS = productionPlanService.list(planMap);
            plansMapById = planDOS.stream().collect(Collectors.toMap(ProductionPlanDO::getId, v -> v, (v1, v2) -> v1));

        }
        List<ProductionPlanDO> saveVo = new ArrayList<>();
        ProductionPlanDO planDO = productionPlanService.get(planId);
        BigDecimal lotNoCount = ObjectUtils.isEmpty(planDO.getLotNoCount()) ? BigDecimal.ZERO : planDO.getLotNoCount();
        planDO.setLotNoCount(lotNoCount.add(new BigDecimal(integers.size())));
        saveVo.add(planDO);
        MaterielDO materielDO = materielService.get(planDO.getMaterielId());
        List<AslBarCodeDO> resultList = service.listByIds(integers);
        if (ObjectUtils.isEmpty(resultList)){
            return R.error("未查询到条码数据");
        }

        for (int i = 0; i < resultList.size(); i++){
            AslBarCodeDO bar = resultList.get(i);
            if (!ObjectUtils.isEmpty(bar.getUuid())){
                ProductionPlanDO planDO1 = plansMapById.get(bar.getUuid());
                if (!ObjectUtils.isEmpty(planDO1)){
                    BigDecimal count = ObjectUtils.isEmpty(planDO.getLotNoCount()) ? BigDecimal.ZERO : planDO.getLotNoCount();
                    planDO1.setLotNoCount(count.subtract(BigDecimal.ONE));
                    saveVo.add(planDO1);
                }

            }
            bar.setUuid(planDO.getId());
            bar.setProductionPlanNo(planDO.getPlanNo());
            bar.setProductId(materielDO.getId());
            bar.setProductCode(materielDO.getSerialNo());
            bar.setProductModel(materielDO.getSpecification());
            bar.setBagging(1);
            bar.setTrayId(0l);
            bar.setScrapStatus(0);
//            bar.setStatus(1);
            bar.setDelFlag(0);

        }
        service.batchUpdate(resultList);
        productionPlanService.batchUpdateForLotNo(saveVo);
        return R.ok("操作成功");
    }

    public static void main(String[] args) {
        BigDecimal zero = BigDecimal.ZERO;
        BigDecimal subtract = zero.subtract(BigDecimal.ONE);
        System.out.println(subtract);
    }

    /**
     * 清除
     * @param ids
     * @return
     */
    @ApiOperation("清除")
    @EvApiByToken(value = "/apis/aslBarCode/clearAway", method = RequestMethod.POST, apiTitle = "清除")
    @Transactional
    public R clearAway(@ApiParam(value = "条码管理主键ID数组", required = true) @RequestParam(value = "ids",defaultValue = "") Long[] ids) {
        AslBarCodeParam param = new AslBarCodeParam();
        param.setOffset(null);
        param.setLimit(null);
        param.setIds(ids);
//        param.setBagging(AslConstant.YES);
        List<AslBarCodeDO> resultList = service.list(param);
        List<Long> trayIds = resultList.stream().filter(bar -> !ObjectUtils.isEmpty(bar.getTrayId()) && !bar.getTrayId().equals(0l)).map(AslBarCodeDO::getTrayId).distinct().collect(Collectors.toList());
        List<Long> planIds = resultList.stream().filter(bar -> !ObjectUtils.isEmpty(bar.getUuid())).map(AslBarCodeDO::getUuid).distinct().collect(Collectors.toList());

        List<AslBarCodeTrayDO> updateTrayList = new ArrayList<>(); //条码绑定的托盘
        Map<Long, AslBarCodeTrayDO> traysById = new HashMap<>();
        if (!ObjectUtils.isEmpty(trayIds)){
            AslBarCodeTrayParam barCodeTrayParam = new AslBarCodeTrayParam();
            barCodeTrayParam.setIds2(trayIds);
            updateTrayList = service.trayList(barCodeTrayParam);
            traysById = updateTrayList.stream().collect(Collectors.toMap(tray -> tray.getId(), tray -> tray));
        }
        List<ProductionPlanDO> planDOS = new ArrayList<>(); //条码绑定的生产计划
        Map<Long, ProductionPlanDO> plansById = new HashMap<>();
        if (!ObjectUtils.isEmpty(planIds)){
            HashMap<String, Object> planMap = new HashMap<>();
            planMap.put("ids",planIds);
//            planDOS = productionPlanService.list(planMap);
        }

        for (AslBarCodeDO entity : resultList) {
            if (!ObjectUtils.isEmpty(traysById) && ObjectUtil.isNotEmpty(entity.getTrayId()) && traysById.containsKey(entity.getTrayId())){
                AslBarCodeTrayDO trayDO = traysById.get(entity.getTrayId());
                trayDO.setSum(ObjectUtils.isEmpty(trayDO.getSum()) ? 0 : (trayDO.getSum() - 1));
                if (trayDO.getSum().compareTo(0) <= 0) trayDO.setStatus(0);
            }
            entity.setTrayId(0l);
            entity.setScrapStatus(AslConstant.NO);
            entity.setStatus(AslConstant.ZERO);
        }
        service.batchUpdateTrays(updateTrayList);
        service.batchUpdate(resultList);
        return R.ok("清除成功！");
    }

    /**
     * 报废
     * @param id
     * @return
     */
    @ApiOperation("报废")
    @EvApiByToken(value = "/apis/aslBarCode/scrap", method = RequestMethod.POST, apiTitle = "报废")
    public R scrap(@ApiParam(value = "条码管理主键ID", required = true) @RequestParam(value = "id", defaultValue = "") Long id) {
        AslBarCodeDO entity = service.get(id);
        entity.setScrapStatus(AslConstant.ONE);
        service.update(entity);
        return R.ok("报废成功！");
    }
}
